package h0830;

import java.util.Scanner;

public class TheKthNumInArray {
    public static void main(String[] args) {
        int[] nums = {7,6,5,4,3,2,1};
        int k = 2;
        int res = quickSelect(nums, 0, nums.length - 1, k);
        System.out.println(res);
    }

    private static int quickSelect(int[] nums, int left, int right, int k) {
        if (left == right) {
            return nums[left];
        }
        int pivotIndex = partition(nums, left, right);
        if (pivotIndex == nums.length - k) {
            return nums[pivotIndex];
        } else if (pivotIndex > nums.length - k) {
            return quickSelect(nums, left, pivotIndex - 1, k);
        } else {
            return quickSelect(nums, pivotIndex + 1, right, k);
        }
    }

    private static int partition(int[] nums, int left, int right) {
        int pivot = nums[left];
        int i = left;
        int j = right;
        while (i <= j) {
            //TODO 这里不能是nums[left] <= pivot，会导致数组下标越界，最后返回的结果就不一样了。因为交换之后i有可能会遍历到pivot的新位置。
            while (i <= right && nums[i] <= pivot) {
                i++;
            }
            while (j >= 0 && nums[j] > pivot) {
                j--;
            }
            if (i >= j) {
                break;
            }
            swap(nums, i, j);
            i++;
            j--;
        }
        swap(nums,left,j);
        //当i>j后，返回j
        return j;
    }

    private static void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
